package org.yray.bean;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class SpringUtil implements ApplicationContextAware {
    private static final Logger log = LoggerFactory.getLogger(SpringUtil.class);
    private static ApplicationContext applicationContext;

    public SpringUtil() {
    }

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        log.info("SpringUtil.init...");
        if (SpringUtil.applicationContext == null) {
            SpringUtil.applicationContext = applicationContext;
        }

    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static Object getBean(String name) {
        if (getApplicationContext() == null) {
            log.error("the applicationContext is null ");
            return null;
        } else {
            return getApplicationContext().getBean(name);
        }
    }

    public static <T> T getBean(Class<T> clazz) {
        if (getApplicationContext() == null) {
            log.error("the applicationContext is null ");
            return null;
        } else {
            return getApplicationContext().getBean(clazz);
        }
    }

    public static <T> T getBean(String name, Class<T> clazz) {
        if (getApplicationContext() == null) {
            log.error("the applicationContext is null ");
            return null;
        } else {
            return getApplicationContext().getBean(name, clazz);
        }
    }

    public static <T> ObjectProvider<T> getBeanProvider(Class<T> clazz) {
        if (getApplicationContext() == null) {
            log.error("the applicationContext is null ");
            return null;
        } else {
            return getApplicationContext().getBeanProvider(clazz);
        }
    }
}